<template>
  <FormItem v-bind="formItemProps" :rules="computeRules" :disabled="inputDisabled">
    <template #default>
      <slot>
        <ElInput
          :class="{ 'is-readonly': readonlyGrey && readonly }"
          :value="value"
          :readonly="readonly"
          :maxlength="maxLength"
          :disabled="inputDisabled"
          clearable
          :placeholder="inputDisabled ? '' : computePlaceholder"
          v-bind="inputProps"
          v-on="listeners"
          @clear="clear"
          @input="emitInput">
          <template #append>
            <slot name="append"></slot>
          </template>
        </ElInput>
        <div v-if="isValidValue && $slots.warn" class="el-form-item__warn">
          <slot name="warn"></slot>
        </div>
      </slot>
    </template>
    <template #error="{ error }">
      <div v-if="$scopedSlots.error && $scopedSlots.error(error)" class="el-form-item__error">
        <slot name="error" :error="error">{{ error }}</slot>
      </div>
    </template>
    <template #label>
      <slot name="label"></slot>
    </template>
    <template #tips>
      <slot name="tips"></slot>
    </template>
  </FormItem>
</template>

<script>
  import formInput from './form-input'
  import { Input } from 'element-ui'
  import { filterProperties, normalizeProps, validateProp } from '@/util'

  const autoBindKeys = Object.keys(Input.props).filter(key => !['value', 'placeholder', 'disabled'].includes(key))

  export default {
    name: 'FormInput',
    mixins: [formInput],
    props: {
      value: [String, Number],
      readonlyGrey:{
        type: Boolean,
        default: true
      },
      maxLength: {
        type: String,
        default: '255'
      }
    },
    data() {
      return {
        isValidValue: false
      }
    },
    computed: {
      inputProps() {
        return filterProperties({ ...normalizeProps(this.$attrs), ...this.$props }, autoBindKeys)
      }
    },
    watch: {
      async value(newVal) {
        this.isValidValue = await validateProp(this.prop, newVal, this.computeRules)
      }
    },
    methods: {
      emitInput(val) {
        this.$emit('input', val)
      },
      clear() {
        this.$emit('clear')
      }
    }
  }
</script>
